import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import Validation from 'backbone-validation'
import {
    getProductCollectionHtml,
} from './custom_views';
import DropDownWidget from 'widgets/DropDownWidget';

import ErrorView from 'base/views/ErrorView';
import ButtonCollectionWidget from 'widgets/ButtonCollectionWidget';
import ButtonCollection from 'base/models/ButtonCollection';
import ButtonWidget from '../../../../../../widgets/ButtonWidget';

const template = require('./templates/ChapterView.mustache');
const ChapterView = Mn.View.extend({
    template: template,
    className: 'taskline-group row quotation_item border_left_block composite content_double_padding',
    regions: {
        'errors': '.errors',
        'addproduct': {
            el: '.chapter-addproduct',
            replaceElement: true
        },
        'addwork': {
            el: '.chapter-addwork',
            replaceElement: true
        }
    },
    events: {
        'click .btn.edit-chapter': 'onEdit',
        'click .btn.delete-chapter': 'onDelete',
        'click .btn.up-chapter': 'onMoveUp',
        'click .btn.down-chapter': 'onMoveDown',
        // Enfants insérés depuis les Vues en Raw Html (custom_views) et leur template
        // Produits et ouvrage
        'click .btn[data-action="product:duplicate"]': 'onProductDuplicate',
        'click .btn[data-action="product:delete"]': 'onProductDelete',
        'click .btn[data-action="work:additem"]': 'onProductAddWorkItem',
        'click .btn[data-action="product:down"]': 'onProductMoveDown',
        'click .btn[data-action="product:up"]': 'onProductMoveUp',
        'click .btn[data-action="product:change_details"]': "onWorkToggleDetail",
        // Items des ouvrages
        'click .btn[data-action="workitem:edit"]': 'onWorkItemEdit',
        'click .btn[data-action="workitem:duplicate"]': 'onWorkItemDuplicate',
        'click .btn[data-action="workitem:delete"]': 'onWorkItemDelete',
        'click .btn[data-action="workitem:down"]': 'onWorkItemMoveDown',
        'click .btn[data-action="workitem:up"]': 'onWorkItemMoveUp',
    },
    childViewEvents: {
        'action:clicked': "onButtonClicked",
    },
    childViewTriggers: {},
    initialize() {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.user_prefs = Radio.channel('user_preferences');
        this.app = Radio.channel('priceStudyApp');
        this.productCollection = this.model.products;
        this.setupEvents();
    },
    setupEvents() {
        this.listenTo(this.productCollection, 'fetched', () => this.render());
        this.listenTo(this.productCollection, 'saved:display_details', () => this.render());
        this.listenTo(this.model.collection, 'fetched', () => this.render());
        this.listenTo(this.facade, 'bind:validation', () => Validation.bind(this));
        this.listenTo(this.facade, 'unbind:validation', () => Validation.unbind(this));
        this.listenTo(this.model, 'validated:invalid', this.showErrors);
        this.listenTo(this.model, 'validated:valid', this.hideErrors.bind(this));
        this.listenTo(this.productCollection, 'validated:invalid', this.showProductErrors);
    },
    showErrors(model, errors) {
        this.$el.addClass('error');
    },
    hideErrors(model) {
        this.$el.removeClass('error');
    },
    showProductErrors(model, errors) {
        this.$el.addClass('error');
        this.showChildView(
            'errors',
            new ErrorView({
                errors: errors
            })
        );
    },
    showButtons(hasProducts) {
        const buttons = [{
            label: 'Ajouter un produit',
            title: 'Ajouter un produit à ce chapitre',
            icon: 'plus',
            showLabel: true,
            action: 'addproduct',
        }, {
            label: 'Ajouter un ouvrage',
            title: 'Ajouter un ouvrage à ce chapitre',
            icon: 'plus',
            showLabel: true,
            action: 'addwork',
        }];
        if (hasProducts) {
            buttons[0].label = "Produit";
            buttons[0]['css'] = "btn-primary";
            buttons[1].label = "Ouvrage";
            buttons[1]['css'] = "btn-primary";
        }
        let view = new ButtonWidget({
            showLabel: true,
            icon: "plus",
            ...buttons[0]
        });
        this.showChildView('addproduct', view);
        view = new ButtonWidget({
            showLabel: true,
            icon: "plus",
            ...buttons[1]
        });
        this.showChildView('addwork', view);
    },
    onRender() {
        const hasProducts = this.productCollection.length > 0;
        this.showButtons(hasProducts);
    },
    templateContext() {
        // Collect data sent to the template (model attributes are already transmitted)
        let min_order = this.model.collection.getMinOrder();
        let max_order = this.model.collection.getMaxOrder();
        let order = this.model.get('order');
        const productHtml = getProductCollectionHtml(this.productCollection)
        return {
            is_not_first: order != min_order,
            is_not_last: order != max_order,
            edit: this.getOption('edit'),
            collectionRawHtml: productHtml,
            total_ht: this.user_prefs.request('formatAmount', this.model.get('total_ht'), true)
        };
    },
    onButtonClicked(action) {
        this.app.trigger('navigate', 'chapters' + '/' + this.model.get('id') + '/' + action);
    },
    onEdit() {
        this.app.trigger('navigate', 'chapters' + '/' + this.model.get('id'));
    },
    onDelete() {
        this.app.trigger('chapter:delete', this.model);
    },
    onMoveUp() {
        this.app.trigger('model:move:up', this.model);
    },
    onMoveDown() {
        this.app.trigger('model:move:down', this.model);
    },
    /**
     * Product RawHtml subviews events management
     * 
     * @param {Event} event : The click event
     * 
     * @returns : The product Instance
     */
    getProductFromEvent(event) {
        const tag = $(event.currentTarget)
        const productId = parseInt(tag.data('id'));
        return this.productCollection.get(productId);
    },
    onProductDuplicate(event) {
        const product = this.getProductFromEvent(event);
        this.app.trigger('product:duplicate', product, this.model.get('id'));
    },
    onProductDelete(event) {
        const product = this.getProductFromEvent(event);
        this.app.trigger('product:delete', product)
    },
    onProductAddWorkItem(event) {
        const product = this.getProductFromEvent(event);
        this.app.trigger('work:additem', product);
    },
    onProductMoveDown(event) {
        const product = this.getProductFromEvent(event);
        this.app.trigger('model:move:down', product)
    },
    onProductMoveUp(event) {
        const product = this.getProductFromEvent(event);
        this.app.trigger('model:move:up', product)
    },
    onWorkToggleDetail(event) {
        const product = this.getProductFromEvent(event);
        const display = product.get('display_details');
        const newValues = {
            'display_details': !display
        }
        product.save(newValues);
    },
    /**
     * WorkItem RawHtml Subviews event management
     * 
     */
    /**
     * 
     * @param {Event} event : The onclick event
     * @returns A WorkItemModel instance
     */
    getWorkItemFromEvent(event) {
        const tag = $(event.currentTarget);
        const workId = parseInt(tag.data('workid'));
        const workItemId = parseInt(tag.data('id'));

        const workModel = this.productCollection.get(workId);
        return workModel.items.get(workItemId);
    },
    onWorkItemEdit(event) {
        const model = this.getWorkItemFromEvent(event);
        this.app.trigger('workitem:edit', model);
    },
    onWorkItemDuplicate(event) {
        const model = this.getWorkItemFromEvent(event);
        this.app.trigger('workitem:duplicate', model);
    },
    onWorkItemDelete(event) {
        const model = this.getWorkItemFromEvent(event);
        this.app.trigger('workitem:delete', model);
    },
    onWorkItemMoveDown(event) {
        const model = this.getWorkItemFromEvent(event);
        this.app.trigger('model:move:down', model);
    },
    onWorkItemMoveUp(event) {
        const model = this.getWorkItemFromEvent(event);
        this.app.trigger('model:move:up', model);
    }
});
export default ChapterView